package com.cloud.order.interception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.bean.R;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * @author 韩先楚
 */
@Component
public class MyBlockInterceptionHander implements BlockExceptionHandler {

    //sentinel拦截对接口的请求，并返回自定义的错误信息
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(429);
        ObjectMapper mapper = new ObjectMapper();
        PrintWriter writer = httpServletResponse.getWriter();
        R r = new R();
        r.setCode(500);
        r.setMsg("sentinel限流了,原因是: "+ e.getMessage());
        String s1 = mapper.writeValueAsString(r);
        writer.write(s1);
    }
}
